<template>
  <div class="details">
    <!-- 导航条 -->
    <div class="detail_nav">
      <ul class="detail_tabs" v-if="type !== 'normal'">
        <li @click="scroll('topL')">
          <a href="javascript:;">商品</a>
        </li>
        <li @click="scroll('sku')">
          <a href="javascript:;">规格</a>
        </li>
        <li @click="scroll('detail')"><a href="javascript:;">详情</a></li>
      </ul>
      <div class="detail_input" v-else>
        <input type="text" placeholder="输入关键字" />
      </div>
    </div>
    <!-- 轮播图 -->
    <div class="targetScroll" ref="topL">
      <van-swipe class="sliderImages" :autoplay="3000" indicator-color="red">
        <van-swipe-item v-for="slider in sliderImages" :key="slider.id">
          <img :src="slider" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <!-- 商品描述 -->
    <div v-if="baseInfo">
      <kill v-if="type == 'seckill'" :base-info="baseInfo"></kill>
      <pin-t v-if="type == 'pt'" :base-info="baseInfo"></pin-t>
      <normal v-if="type == 'normal'" :base-info="baseInfo"></normal>
    </div>
    <!-- 商品规格 -->
    <div
      ref="sku"
      class="sku targetScroll"
      v-if="Object.keys(curSku).length"
      @click="show = !show"
    >
      <p>已选择:</p>
      <div class="sku-info">
        <p>
          <span>{{ Object.keys(curSku)[0] }}</span
          ><span>&gt;</span>
        </p>
        <div>
          <img v-for="(src, i) in skuImgs" :key="i" :src="src" alt="" />
          <span>共{{ totalSkus }}种规格可选</span>
        </div>
      </div>
    </div>
    <van-action-sheet v-model="show" v-if="Object.keys(curSku).length">
      <div class="content">
        <div class="cheader">
          <img :src="Object.values(curSku)[0].image" alt="" />
          <div class="cheader-info">
            <h3>{{ baseInfo.storeName }}</h3>
            <h2>￥{{ Object.values(curSku)[0].price }}</h2>
            <p>库存：{{ Object.values(curSku)[0].stock }}</p>
          </div>
        </div>
        <div class="skus">
          <div
            class="sku-info"
            v-for="(sku, j) in goodsInfo.productAttr"
            :key="sku.id"
          >
            <h3>{{ sku.attrName }}</h3>
            <ul>
              <li
                :class="{
                  active: Object.keys(curSku)[0].split(',')[j] === attr,
                }"
                v-for="attr in sku.attrValues.split(',')"
                :key="attr"
                @click="setCurSku(attr, j)"
              >
                {{ attr }}
              </li>
            </ul>
          </div>
        </div>
        <div class="nums">
          <span>数量</span>
          <div class="count">
            <span @click="setNums('minus')">-</span>
            <input type="text" v-model="nums" />
            <span @click="setNums('add')">+</span>
          </div>
        </div>
        <div class="buttons">
          <van-button type="info" @click="addCart">加入购物车</van-button>
          <van-button type="warning">立即购买</van-button>
        </div>
      </div>
    </van-action-sheet>
    <!-- 商品详情 -->
    <div ref="detail" class="detail_data targetScroll">
      <h3>产品详情</h3>
      <div v-html="detailStr"></div>
    </div>
    <!-- 底部tabbar -->
    <div class="tabbars">
      <span>收藏</span>
      <p @click="$router.push('/cart')">
        购物车<span>({{ this.nums }})</span>
      </p>
    </div>
  </div>
</template>

<script>
import Kill from "@/components/Kill.vue";
import PinT from "@/components/PinT.vue";
import Normal from "@/components/Normal.vue";
export default {
  name: "Details",
  data() {
    return {
      type: "", // 详情页类型：秒杀、拼团惠、普通商品
      id: "", // 商品id
      goodsInfo: null, // 商品详情对象
      sliderImages: [], // 轮播图数据
      baseInfo: null, // 商品的基本信息
      show: false,
      skuImgs: [], // 规格缩略图
      totalSkus: 0, // 规格总数量
      curSku: {}, // 默认选中规格
      detailStr: "", // 商品详情介绍
      initImgWidth: true,
      nums: 1, // 购物车数量
    };
  },
  created() {
    this.type = this.$route.query.type;
    this.id = this.$route.params.id;
    let url = "";
    switch (this.type) {
      case "seckill":
        url = `https://apif.java.crmeb.net/api/front/seckill/detail/${this.id}`;
        break;
      case "pt":
        url = `https://apif.java.crmeb.net/api/front/combination/detail/${this.id}`;
        break;
      case "normal":
        url = `https://apif.java.crmeb.net/api/front/product/detail/${this.id}?type=normal`;
        break;
      default:
        break;
    }
    this.$axios.get(url).then(({ data }) => {
      this.goodsInfo = data.data;
      if (this.type == "seckill") {
        const res = this.goodsInfo.storeSeckill;
        this.sliderImages = JSON.parse(res.sliderImage);
        this.baseInfo = {
          sales: res.sales,
          storeName: res.storeName,
          unitName: res.unitName,
        };
        this.detailStr = res.content;
      } else if (this.type == "pt") {
        const res = this.goodsInfo.storeCombination;
        this.detailStr = res.content;
        this.sliderImages = JSON.parse(res.sliderImage);
        this.baseInfo = {
          people: res.people,
          price: res.price,
          otPrice: res.otPrice,
          storeName: res.storeName,
          unitName: res.unitName,
          sales: res.sales,
        };
      } else if (this.type == "normal") {
        const res = this.goodsInfo.productInfo;
        this.detailStr = res.content;
        this.sliderImages = JSON.parse(res.sliderImage);
        this.baseInfo = {
          price: res.price,
          otPrice: res.otPrice,
          storeName: res.storeName,
          unitName: res.unitName,
          sales: res.sales,
          stock: res.stock,
          vipPrice: res.vipPrice,
        };
      }
      // 处理页面中已选择部分：默认选中规格和规格缩略图
      const skuItems = this.goodsInfo.productValue;
      this.totalSkus = Object.keys(skuItems).length;
      Object.keys(skuItems)
        .slice(0, 4)
        .forEach(sku => {
          this.skuImgs.push(skuItems[sku].image);
        });
      this.curSku[Object.keys(skuItems)[0]] =
        skuItems[Object.keys(skuItems)[0]];
    });
    this.$axios
      .get(
        "https://apif.java.crmeb.net/api/front/cart/count?numType=true&type=total"
      )
      .then(({ data }) => {
        console.log(data);
        this.nums = data.data.count;
      });
  },
  updated() {
    if (this.initImgWidth) {
      Array.from(document.querySelectorAll(".detail_data img")).forEach(img => {
        img.style.width = "100vw";
      });
      this.initImgWidth = false;
    }
  },
  methods: {
    setCurSku(attr, idx) {
      const oldKeys = Object.keys(this.curSku)[0].split(",");
      oldKeys[idx] = attr;
      const newKeys = oldKeys.join(",");
      this.curSku = {
        [newKeys]: this.goodsInfo.productValue[newKeys],
      };
    },
    scroll(id) {
      // console.log(this.$refs[id]);
      // scrollIntoView：它总是将目标元素滚动到容器的顶部位置。
      this.$refs[id].scrollIntoView(true);
    },
    addCart() {
      let curGoods = Object.values(this.curSku)[0];
      if (this.type == "normal") {
        this.savCart(curGoods);
      } else {
        // 判断：如果当前详情是秒杀和拼团惠，这个curGoods记录的规格id和productId不是真正加入购物车的id。
        let productID = 0; // 记录真正加入购物车的产品id
        let skuID = 0; // 记录正加入购物车的规格id
        if (this.type == "pt") {
          productID = this.goodsInfo.storeCombination.productId;
        } else if (this.type == "seckill") {
          productID = this.goodsInfo.storeSeckill.productId;
        }

        this.$axios
          .get(
            `https://apif.java.crmeb.net/api/front/product/detail/${productID}?type=normal`
          )
          .then(({ data }) => {
            // 已当前选中的规格作为键，从真实的产品对象中获取商品
            curGoods = data.data.productValue[Object.keys(this.curSku)[0]];
            this.savCart(curGoods);
          });
      }
    },
    savCart(curGoods) {
      this.$axios
        .post("https://apif.java.crmeb.net/api/front/cart/save", {
          cartNum: this.nums,
          isNew: false,
          productAttrUnique: curGoods.id, // 商品规格id
          productId: curGoods.productId, // 当前商品id,
        })
        .then(({ data }) => {
          // 隐藏弹出框
          this.show = false;
        });
    },
    setNums(type) {
      switch (type) {
        case "minus":
          if (this.nums > 1) this.nums--;
          else alert("至少选择一件");
          break;
        case "add":
          this.nums++;
          break;
        default:
          break;
      }
    },
  },
  components: {
    Kill,
    PinT,
    Normal,
  },
};
</script>

<style lang="scss" scoped>
.details {
  height: calc(100vh - 141px);
  overflow-y: scroll;
  &::-webkit-scrollbar {
    display: none;
  }
  .targetScroll {
    padding-top: 40px;
    margin-top: -40px;
  }
}
.detail_nav {
  height: 40px;
  background-color: yellow;
  position: sticky;
  top: -1px;
  left: 0;
  z-index: 1000;
  > ul {
    height: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
  > .detail_input {
    height: 40px;
    background-color: yellow;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.sliderImages {
  img {
    width: 100vw;
    height: 375px;
  }
}
.sku {
  width: 90vw;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  > p {
    width: 70px;
  }
  > div {
    width: calc(100% - 70px);
    > p {
      display: flex;
      justify-content: space-between;
    }
    > div {
      display: flex;
      align-items: center;
    }
    img {
      width: 33px;
      height: 33px;
    }
  }
}
.van-action-sheet__content {
  &::-webkit-scrollbar {
    display: none;
  }
}
.content {
  padding: 10px;

  .cheader {
    display: flex;
    justify-content: space-between;
    img {
      width: 75px;
      height: 75px;
    }
    h3 {
      width: 280px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
  .sku-info {
    margin: 20px 0;
    h3 {
      height: 30px;
      line-height: 30px;
    }
    ul {
      display: flex;
      flex-wrap: wrap;
      li {
        font-size: 14px;
        padding: 5px 10px;
        border-radius: 15px;
        background-color: lightblue;
        margin-right: 10px;
        margin-bottom: 10px;
        &.active {
          color: blue;
          border: 1px solid blue;
        }
      }
    }
  }
  .nums {
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .count {
      display: flex;
      align-items: center;
      input {
        width: 20px;
        padding: 5px 10px;
        outline: none;
        border: 1px solid lightblue;
        text-align: center;
        margin: 0 10px;
      }
    }
  }
  .buttons {
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    button {
      width: 50%;
    }
  }
}
.detail_data {
  margin-top: 20px;
  h3 {
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
}
.tabbars {
  width: 100vw;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  position: fixed;
  bottom: 0;
  left: 0;
  background-color: lightblue;
}
</style>
